﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;

namespace Tododoo.Helpers
{
    public class FocusEx
    {
        #region FocusOnVisibleProperty

        public static bool GetFocusOnVisible(DependencyObject obj)
        {
            return (bool)obj.GetValue(FocusOnVisibleProperty);
        }

        public static void SetFocusOnVisible(DependencyObject obj, bool value)
        {
            obj.SetValue(FocusOnVisibleProperty, value);
        }

        // Using a DependencyProperty as the backing store for FocusOnVisible.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty FocusOnVisibleProperty =
            DependencyProperty.RegisterAttached("FocusOnVisible", typeof(bool), typeof(FocusEx), new UIPropertyMetadata(false, OnFocusOnVisibleChanged));

        private static void OnFocusOnVisibleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var el = d as UIElement;
            if (el == null) return;

            if ((bool)e.NewValue)
            {
                el.IsVisibleChanged += new DependencyPropertyChangedEventHandler(el_IsVisibleChanged);
            }
            else
            {
                el.IsVisibleChanged -= new DependencyPropertyChangedEventHandler(el_IsVisibleChanged);
            }
        }

        static void el_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            ((UIElement)sender).Focus();
        }

        #endregion
    }
}
